<template>
    <!--地图挂载dom-->
    <div id="map">
    </div>
</template>

<script>
    //引入依赖
    import {Map, View, Feature} from 'ol'
    import GeoJSON from 'ol/format/GeoJSON';
    import {ImageCanvas, OSM, Vector as VectorSource} from 'ol/source'
    import {Circle as CircleStyle, Fill, Stroke, Style} from 'ol/style';
    import {Image as ImageLayer, Tile as TileLayer, Vector as VectorLayer} from 'ol/layer';
    import {Polygon} from 'ol/geom'
    import * as turf from '@turf/turf';
    //import kriging from '@sakitam-gis/kriging';
    import kriging from '../lib/kriging';
    import gz from '../data/广州市'
    import GZ from '../data/GZ'

    //定义使用颜色值表示最大值与最小值的范围
    let colors =
        [{min: -50, max: -45, color: "#2e0057"},
            {min: -45, max: -40, color: "#4a008b"},
            {min: -40, max: -35, color: "#0d0b66"},
            {min: -35, max: -30, color: "#0c2695"},
            {min: -30, max: -25, color: "#0c43c4"},
            {min: -25, max: -20, color: "#1a6bd7"},
            {min: -20, max: -15, color: "#3492f4"},
            {min: -15, max: -10, color: "#67b7f7"},
            {min: -10, max: -5, color: "#96cef4"},
            {min: -5, max: -0, color: "#c1e6f9"},
            {min: 0, max: 5, color: "#fefec6"},
            {min: 5, max: 10, color: "#f8f1a1"},
            {min: 10, max: 15, color: "#ffe479"},
            {min: 15, max: 20, color: "#ffcc4f"},
            {min: 20, max: 25, color: "#f19906"},
            {min: 25, max: 30, color: "#f07609"},
            {min: 30, max: 35, color: "#eb481f"},
            {min: 35, max: 40, color: "#ab0110"},
            {min: 40, max: 45, color: "#650015"},
            {min: 45, max: 50, color: "#44000b"}];

    let canvasLayer = null;
    export default {
        name: 'ProjectKriging',
        data() {
            return {
                map: null,
            }
        },
        mounted() {

            const image = new CircleStyle({
                radius: 5,
                fill: null,
                stroke: new Stroke({
                    color: 'red',
                    width: 1
                }),
            });

            const styles = {
                'Point': new Style({
                    image: image,
                }),
                'LineString': new Style({
                    stroke: new Stroke({
                        color: 'green',
                        width: 1,
                    }),
                }),
                'MultiLineString': new Style({
                    stroke: new Stroke({
                        color: 'green',
                        width: 1,
                    }),
                }),
                'MultiPoint': new Style({
                    image: image,
                }),
                'MultiPolygon': new Style({
                    stroke: new Stroke({
                        color: 'yellow',
                        width: 1,
                    }),
                    fill: new Fill({
                        color: 'rgba(255, 255, 0, 0.1)',
                    }),
                }),
                'Polygon': new Style({
                    stroke: new Stroke({
                        color: 'blue',
                        lineDash: [4],
                        width: 3,
                    }),
                    fill: new Fill({
                        color: 'rgba(0, 0, 255, 0.1)',
                    }),
                }),
                'GeometryCollection': new Style({
                    stroke: new Stroke({
                        color: 'magenta',
                        width: 2,
                    }),
                    fill: new Fill({
                        color: 'magenta',
                    }),
                    image: new CircleStyle({
                        radius: 10,
                        fill: null,
                        stroke: new Stroke({
                            color: 'magenta',
                        }),
                    }),
                }),
                'Circle': new Style({
                    stroke: new Stroke({
                        color: 'red',
                        width: 2,
                    }),
                    fill: new Fill({
                        color: 'rgba(255,0,0,0.2)',
                    }),
                }),
            };

            const styleFunction = function (feature) {
                return styles[feature.getGeometry().getType()];
            };

            this.osm = new TileLayer({
                source: new OSM(),
            });
            this.map = new Map({
                target: 'map',//指定挂载dom，注意必须是id
                layers: [
                    this.osm
                ],
                //配置视图
                view: new View({
                    center: [113.24981689453125, 26.126468438108688],   //视图中心位置
                    projection: "EPSG:4326", //指定投影
                    zoom: 5   //缩放到的级别
                })
            });

            // to do 绘制好边界线
            let vectorLayer = new VectorLayer({
                imageRatio: 2,
                source: new VectorSource({
                    url: 'https://geo.datav.aliyun.com/areas_v3/bound/geojson?code=440100_full',
                    format: new GeoJSON(),
                }),
                style: styleFunction,
            });

            this.map.addLayer(vectorLayer);

            //首次加载，自动渲染一次差值图
            let coordinates = GZ.geometries[0].coordinates;
            let polygon = turf.polygon(coordinates);
            let bbox = turf.bbox(polygon);
            //绘制克里金
            this.drawKriging(bbox);
        },
        methods: {
            drawKriging(extend) {
                //存储值与经纬度
                let values = [], longitudes = [], latitudes = [];
                let features = gz.features;
                for (const feature of features) {
                    //中心点
                    let center = feature.properties.center;
                    //随机生成数值
                    values.push(this.getRandom(-50, 50));
                    longitudes.push(center[0]);
                    latitudes.push(center[1]);
                }

                if (values.length > 3) {
                    //克里金训练
                    let coordinates = GZ.geometries[0].coordinates;
                    let variogram = kriging.train(values, longitudes, latitudes, 'exponential', 0, 100);
                    //使用刚才的variogram对象使polygons描述的地理位置内的格网元素具备不一样的预测值；
                    let grid = kriging.grid(coordinates, variogram, (extend[2] - extend[0]) / 1000);

                    //创建新图层
                    canvasLayer = new ImageLayer({
                        source: new ImageCanvas({
                            canvasFunction: (extent, resolution, pixelRatio, size, projection) => {
                                console.log(extent);
                                let canvas = document.createElement('canvas');
                                canvas.width = size[0];
                                canvas.height = size[1];
                                canvas.style.display='block';
                                //设置canvas透明度
                                canvas.getContext('2d').globalAlpha=0.75;
                                kriging.plot(canvas, grid, [extent[0], extent[2]], [extent[1], extent[3]], colors);
                                return canvas;
                            },
                            projection: 'EPSG:4326'
                        })
                    })
                    //向map添加图层
                    this.map.addLayer(canvasLayer);
                }
            },
            getRandom(min, max) {
                let num = Math.floor(Math.random() * (max - min + 1) + min)
                return num
            },
        }
    }
</script>

<style scoped>
    #map {
        width: 100%;
        height: 100%;
    }
</style>
